package com.tengju.user.infrastructure.repository.club;

import com.tengju.user.domain.model.club.Zone;
import com.tengju.user.domain.model.club.ZoneId;
import com.tengju.user.domain.model.club.ZoneRepository;
import com.tengju.user.domain.shared.JsonUtil;
import com.tengju.user.infrastructure.persistence.mybatis.dataobject.ZoneDO;
import com.tengju.user.infrastructure.persistence.mybatis.mapper.dealer.custom.ZoneMapper;
import com.tengju.user.infrastructure.repository.convert.ZoneConvert;
import com.tengju.user.infrastructure.shared.InfraException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Repository
public class ZoneRepositoryImpl implements ZoneRepository {

    @Resource
    private ZoneMapper zoneMapper;

    @Override
    public boolean addZone(Zone zone) {
        ZoneDO zoneDO = ZoneConvert.convert(zone);
        zoneDO.setCreateTime(new Date());
        zoneDO.setUpdateTime(new Date());
        if (zoneMapper.insert(zoneDO) != 1) {
            throw new InfraException("添加战区失败");
        }
        return true;
    }

    @Override
    public Zone findByName(String name) {
        ZoneDO zoneDO = zoneMapper.queryByName(name);
        return ZoneConvert.convert(zoneDO);
    }

    @Override
    public Zone findById(Long id) {
        ZoneDO zoneDO = zoneMapper.queryById(id);
        return ZoneConvert.convert(zoneDO);
    }

    @Override
    public boolean editZone(Zone zone) {
        ZoneDO zoneDO = ZoneConvert.convert(zone);
        if (zoneMapper.updateNameAndHeadImg(zoneDO) != 1) {
            throw new InfraException("编辑战区失败");
        }
        return true;
    }

    @Override
    public List<Zone> findByPage(Integer offset,Integer pageSize) {
        List<ZoneDO> zoneDOList = zoneMapper.queryByPage(offset,pageSize);
        if (CollectionUtils.isEmpty(zoneDOList)) {
            return null;
        }
        return zoneDOList.stream().map(ZoneConvert::convert).collect(Collectors.toList());
    }

    @Override
    public Integer count() {
        return zoneMapper.count();
    }

    @Override
    public boolean delZone(ZoneId zoneId) {
        int delete = zoneMapper.delete(zoneId.getValue());
        if (delete != 1) {
            throw new InfraException("删除战区异常");
        }

        return true;
    }
}
